import 'package:flutter/material.dart';
import 'package:photo_view/photo_view.dart';
import '../models/image_file.dart';
import '../widgets/video_player_widget.dart';

class MediaDetailScreen extends StatefulWidget {
  final List<MediaFile> mediaFiles;
  final int initialIndex;

  const MediaDetailScreen({
    super.key,
    required this.mediaFiles,
    required this.initialIndex,
  });

  @override
  State<MediaDetailScreen> createState() => _MediaDetailScreenState();
}

class _MediaDetailScreenState extends State<MediaDetailScreen> {
  late PageController _pageController;
  late int _currentIndex;

  @override
  void initState() {
    super.initState();
    _currentIndex = widget.initialIndex;
    _pageController = PageController(initialPage: widget.initialIndex);
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  String _formatFileSize(int bytes) {
    if (bytes < 1024) return '$bytes B';
    if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB';
    return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
  }

  Widget _buildMediaView(MediaFile mediaFile) {
    if (mediaFile.type == MediaType.image) {
      return PhotoView(
        imageProvider: FileImage(mediaFile.file),
        initialScale: PhotoViewComputedScale.contained,
        minScale: PhotoViewComputedScale.contained * 0.5,
        maxScale: PhotoViewComputedScale.covered * 2.0,
        heroAttributes: PhotoViewHeroAttributes(tag: mediaFile.path),
        errorBuilder: (context, error, stackTrace) {
          return const Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.broken_image, size: 64, color: Colors.white54),
                SizedBox(height: 16),
                Text('图片加载失败', style: TextStyle(color: Colors.white54)),
              ],
            ),
          );
        },
      );
    } else if (mediaFile.type == MediaType.video) {
      return VideoPlayerWidget(videoFile: mediaFile.file);
    } else {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.file_present, size: 64, color: Colors.white54),
            SizedBox(height: 16),
            Text('不支持的文件格式', style: TextStyle(color: Colors.white54)),
          ],
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    final currentMedia = widget.mediaFiles[_currentIndex];

    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.black,
        foregroundColor: Colors.white,
        title: Text(
          '${_currentIndex + 1} / ${widget.mediaFiles.length}',
          style: const TextStyle(color: Colors.white),
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.info_outline),
            onPressed: () {
              showDialog(
                context: context,
                builder: (context) => AlertDialog(
                  title: Text('${currentMedia.type == MediaType.image ? '图片' : '视频'}信息'),
                  content: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('文件名: ${currentMedia.name}'),
                      const SizedBox(height: 8),
                      Text('类型: ${currentMedia.type == MediaType.image ? '图片' : '视频'}'),
                      const SizedBox(height: 8),
                      Text('大小: ${_formatFileSize(currentMedia.size)}'),
                      const SizedBox(height: 8),
                      Text('修改时间: ${currentMedia.lastModified.toString().split('.')[0]}'),
                    ],
                  ),
                  actions: [
                    TextButton(
                      onPressed: () => Navigator.pop(context),
                      child: const Text('关闭'),
                    ),
                  ],
                ),
              );
            },
          ),
        ],
      ),
      body: PageView.builder(
        controller: _pageController,
        onPageChanged: (index) {
          setState(() {
            _currentIndex = index;
          });
        },
        itemCount: widget.mediaFiles.length,
        itemBuilder: (context, index) {
          return _buildMediaView(widget.mediaFiles[index]);
        },
      ),
      bottomNavigationBar: widget.mediaFiles.length > 1
          ? Container(
              color: Colors.black,
              padding: const EdgeInsets.symmetric(vertical: 8.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  IconButton(
                    icon: const Icon(Icons.arrow_back_ios, color: Colors.white),
                    onPressed: _currentIndex > 0
                        ? () {
                            _pageController.previousPage(
                              duration: const Duration(milliseconds: 300),
                              curve: Curves.easeInOut,
                            );
                          }
                        : null,
                  ),
                  Expanded(
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Text(
                          currentMedia.name,
                          style: const TextStyle(color: Colors.white, fontSize: 16),
                          overflow: TextOverflow.ellipsis,
                        ),
                        Text(
                          currentMedia.type == MediaType.image ? '图片' : '视频',
                          style: const TextStyle(color: Colors.white54, fontSize: 12),
                        ),
                      ],
                    ),
                  ),
                  IconButton(
                    icon: const Icon(Icons.arrow_forward_ios, color: Colors.white),
                    onPressed: _currentIndex < widget.mediaFiles.length - 1
                        ? () {
                            _pageController.nextPage(
                              duration: const Duration(milliseconds: 300),
                              curve: Curves.easeInOut,
                            );
                          }
                        : null,
                  ),
                ],
              ),
            )
          : null,
    );
  }
}